<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast" :label-width="120">
			<uni-forms-item name="customer" label="客户名称" required>
				<uni-data-select collection="custom" field="_id as value, name as text" v-model="formData.customer"
					:localdata="range" :page-size="1000"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="factory" label="工厂信息" required>
				<uni-easyinput placeholder="工厂信息" v-model="formData.factory"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="settlement_method" label="结算方式" required>
				<uni-easyinput placeholder="结算方式" v-model="formData.settlement_method"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="currency" label="币种">
				<uni-easyinput placeholder="币种" v-model="formData.currency"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="purchase_order_reminder" label="是否提醒做采购单">
				<switch @change="binddata('purchase_order_reminder', $event.detail.value)"
					:checked="formData.purchase_order_reminder"></switch>
			</uni-forms-item>
			<uni-forms-item name="orders_number" label="订单号" required>
				<uni-easyinput placeholder="请输入订单号" v-model="formData.orders_number"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="delivery_date" label="发货日期">
				<uni-datetime-picker type="type" return-type="timestamp"
					v-model="formData.delivery_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="prepayment_amount" label="预收金额">
				<uni-easyinput v-model="formData.prepayment_amount" type="number" placeholder="请输入金额"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="order_termination" label="是否中止">
				<switch @change="binddata('order_termination', $event.detail.value)"
					:checked="formData.order_termination"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/orders.js';

	const db = uniCloud.database();
	const dbCollectionName = 'orders';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"customer": "",
				"factory": "无",
				"orders_number": "",
				"settlement_method": "银行转账",
				"currency": "RMB",
				"purchase_order_reminder": null,
				"delivery_date": null,
				"prepayment_amount": 0,
				"order_termination": null,
				"updatedAt": null
			}
			return {
				range: [],
				formData,
				formDataId: -1,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			binddata(type, val) {
				if (type == 'purchase_order_reminder') {
					this.formData.purchase_order_reminder = val
				} else {
					this.formData.order_termination = val
				}
			},
			/**
			 * 验证表单并提交
			 */
			submit() {

				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				const timestamp = Date.now(); // 获取当前时间戳
				const year = new Date(timestamp).getFullYear(); // 获取年份
				const month = (new Date(timestamp).getMonth() + 1).toString().padStart(2, '0'); // 获取月份
				const day = new Date(timestamp).getDate().toString().padStart(2, '0'); // 获取日期

				// 使用时间戳的一部分作为订单号的唯一标识
				const uniqueId = timestamp.toString().slice(-8); // 获取时间戳的后6位
				// if (this.formDataId === -1) {
				// 	// 拼接订单号
				// 	value.orders_number = `SY${year}${month}${day}${uniqueId}`;
				// }
				if (this.formDataId == -1) {

					return db.collection(dbCollectionName).add(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '新增成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				} else {
					// 使用 clientDB 提交数据
					return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})

				}

			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"customer,factory,settlement_method,currency,purchase_order_reminder,delivery_date,prepayment_amount,order_termination,updatedAt,orders_number"
				).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data

					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}
</style>